<template>
  <div class="job-notification-item" @click="toJobNotificationDetails(info)">
    <div class="job-notification-item-header">
      <span class="job-notification-item-new" v-if="info.readed == 0"></span>
      <span>{{info.body.title}}</span>
    </div>
    <div
      class="job-notification-item-info"
      name="header"
      v-if="info.body.content"
    >
      <template v-if="isOpenData && info.body.contentStaffId">
        {{infoBodyContent.before}}<open-data type='userName' :openid="info.body.contentStaffId"></open-data>{{infoBodyContent.after}}
      </template>
      <template v-else>
        {{infoBodyContent}}
      </template>
    </div>
    <div class="job-notification-item-content" v-if="infoBodyForms">
        <!-- TODO: 存在中文判断，接口返回，属于展示的内容，需要注意下~ -->
      <p
        v-for="(item, index) in infoBodyForms"
        :key="index"
        :class="{
          'over-ellipsis': item.key === '评论内容：'
      }">
        {{item.key}}
        <template v-if="isOpenData && item.staffIds.length">
          <template v-if="item.staffIds.length === 1">
            {{item.before}}<open-data type='userName' :openid="item.staffIds[0]"></open-data>{{item.after}}
          </template>
          <template v-else>
            <open-data v-for="(sItem, sIndex) in item.staffIds" :key="sIndex" type='userName' :openid="sItem" :class="{'mar-l-6': sIndex >= 1}"></open-data>
          </template>
        </template>

        <!-- 时间戳转为格式化成字符串格式 -->
        <template v-else-if="(typeof item.value === 'number') && ((`${item.value}''`).length === 13)">
          {{ item.value | fmt_datetime }}
        </template>

        <template v-else>
          {{getBodyFormLabel(item.value)}}
        </template>

      </p>
    </div>
    <div class="job-notification-item-footer">
      <p class="job-notification-item-time">{{ info.createTime | fmt_datetime }}</p>
    </div>
  </div>
</template>

<script>
import { isOpenData } from '@src/util/platform'
import * as NotificationApi from '@src/api/NotificationApi';
import platform from '@src/platform';
import { isBasicEditionControl } from '@shb-lib/version'
/* enum */
import { ApproveActionLabelEnum, MessageSourceLabelEnum } from '@model/enum/LabelEnum.ts'

export default {
  name: 'job-notification-item',
  props: {
    info: Object,
    index: Number
  },
  computed: {
    isBasicEditionControl() {
      return isBasicEditionControl()
    },
    infoBodyContent() {
      const { content, contentStaffId } = this.info.body
      if(isOpenData && contentStaffId) {
        return this.reduceOpenDataStaffIdString(content)
      }
      return content.replace('<<', '').replace('>>', '')

    },
    infoBodyForms() {
      const form = (this.info.body.forms || []).map(item => {
        const { key, value, staffId } = item
        const staffIds = staffId ? staffId.split(',') : []
        return Object.assign({ key, value, staffIds }, this.reduceOpenDataStaffIdString(value))
      })
      return form
    }
  },
  data() {
    return {
      isOpenData
    }
  },
  methods: {
    // 获取多语言label
    getBodyFormLabel(name) {
      return ApproveActionLabelEnum[name] || MessageSourceLabelEnum[name] || name
    },
    // 处理opendata <<staffid>>字符串
    reduceOpenDataStaffIdString(valueString) {
      const [start, end] = [valueString.indexOf('<<'), valueString.indexOf('>>')]
      return {
        before: start < 0 ? '' : valueString.slice(0, start),
        after: end < 0 ? '' : valueString.slice(end + 2, valueString.length)
      }
    },

    /** 删除通知 */
    async deleteItem(info) {
      try {
        let params = {
          type: 'work',
          id: info.id
        };
        if (await platform.confirm('确定要删除该信息吗？')) {
          let result = await NotificationApi.deleteNotification(params);
          if (result.status == 0) {
            this.$emit('deleteItem', info, this.index);
          }
        }
      } catch (error) {
        console.error(error);
      }
    },

    /** 打开工作通知详情页 */
    async toJobNotificationDetails(info) {
      try {
        let needHide = false;
        if (this.isBasicEditionControl && info.source !== 'task' && info.source !== 'approve' && info.source !== 'authority' && info.source !== 'attention') {
          this.$emit('clearNum', {
            count: 1,
            id: info.id,
            needHide,
            readed: info.readed
          });
          info.readed = 1;
          return
        }
        // 导入导出成功或失败通知时，弹出后台任务弹窗
        if(info.tag == 'ExportSuccess' || info.tag == 'ImportSuccess' || info.tag == 'ExportFailure' || info.tag == 'ImportFailure') {
          window.parent.showExportList();
          window.parent.exportPopoverToggle(true);
        }else{
          if (info.pcUrl) {
            if(info.source == 'calendar' && info.isDelete) return;
            if (info.source != 'daily' || info.tag === 'qrcode') {
              let itemId = this.getId(info);
              const defaultTitleMap = {
                'exchange': this.$t('common.pageTitle.otherPageTitle.jobNotificationItem.title1'),
                'satisfaction': this.$t('common.pageTitle.otherPageTitle.jobNotificationItem.title2'),
              };
              let title = info.title ? info.title : defaultTitleMap[info.source] || this.$t('common.pageTitle.otherPageTitle.jobNotificationItem.title3');
              if(info.tag === 'qrcode') title = this.$t('common.pageTitle.otherPageTitle.jobNotificationItem.title4');
              if(info.tag === 'PaaSReturnVisit') title = this.$t('common.pageTitle.otherPageTitle.jobNotificationItem.title2')
              if(info.tag === 'SMART_PLAN_TASK_CREATE_ERROR') title = this.$t('common.pageTitle.otherPageTitle.jobNotificationItem.title5')

              const openTapParams = {
                id: itemId,
                title,
                close: true,
                url: info.pcUrl
              }

              // 判断是否是跳转到paas的详情页面 需要刷新
              if(info.pcUrl.includes('/paas/#/template/detail')) {
                openTapParams.reload = true
                openTapParams.viewType = 'vue'
              }

              this.$platform.openTab(openTapParams);
              needHide = true;
              if(info.source == 'calendar') {
                setTimeout(() => {
                  this.$eventBus.$emit('hideNotificationPanel')
                }, 1500);
              }
            } else {
              info.pcUrl = `${info.pcUrl}&DingTalkFlag=false`;
              this.$emit('toDaily', {
                coutn: 1,
                id: info.id,
                url: info.pcUrl,
                readed: info.readed
              });
            }
          }

        }


        this.$emit('clearNum', {
          count: 1,
          id: info.id,
          needHide,
          readed: info.readed
        });
        info.readed = 1;
      } catch (error) {
        console.error(error);
      }
    },
    getId(info) {
      // pcUrl=/security/user?ranKey=123456&select=delete
      // 结算单详情
      if (info.pcUrl.indexOf('/pcResourceManage/settleDetailView') != -1) {
        let strs = info.pcUrl.split('?');
        if(strs && strs.length !== 0) {
          let str = strs[0]
          let urlSplit = str.split('/');
          let params = urlSplit && urlSplit.length !== 0 && urlSplit[urlSplit.length - 1]
          return `settle_view_${params}`;
        }
        return `settle_view_${info.primaryId}`;

      }
      // 订购单详情
      if(info.pcUrl.includes('/purchaaseOrderManage/view')) {
        let urlObj_ = this.$getUrlObj({
          location:{
            href:info.pcUrl
          }
        })
        const {id} = urlObj_;
        return `purchaaseOrderManageView${id}`;
      }
      // 服务商详情
      if(info.pcUrl.includes('/service/manage/provider/detail')) {
        let urlObj_ = this.$getUrlObj({
          location:{
            href:info.pcUrl
          }
        })
        const {id} = urlObj_;
        return `service_provider_detail_${id}`;
      }
      // 工程师详情
      if(info.pcUrl.includes('/service/manage/engineer/detail')) {
        let urlObj_ = this.$getUrlObj({
          location:{
            href:info.pcUrl
          }
        })
        const {id} = urlObj_;
        return `service_engineer_detail_${id}`;
      }
      if (info.pcUrl.indexOf('/security/user') != -1)
        return 'M_JOBTRANSFER_DETAIL';
      if (info.pcUrl.indexOf('/task/view/') != -1)
        return `task_view_${info.primaryId}`;
      if (info.pcUrl.indexOf('/partV2/repertory/record') != -1)
        return 'M_VIP_SPAREPART_RECORD';
      if (info.pcUrl.indexOf('/event/view/') != -1) return 'M_SERVICE_PROJECT';
      if (info.pcUrl.indexOf('/info/notice/detail/page') != -1)
        return `bulletin_detail_${info.primaryId}`;
      if (info.pcUrl.indexOf('/wiki/detail/page') != -1)
        return `document_detail_${info.primaryId}`;
      if (info.pcUrl.indexOf('/im/imChat') != -1)
        return 'M_CHILD_ONLINE_CUSTOMER_SERVICE';
      if (info.pcUrl.indexOf('/calendar') != -1) return 'M_CALENDAR_ALL';
      if (info.pcUrl.indexOf('/product/bhAnalysis') != -1) return 'M_QRCODE_ANALYSIS';
      if (info.pcUrl.split('/').pop().indexOf('home') != -1 || info.pcUrl.indexOf('/foundation/workBench') != -1) return 'M_HOME';
      return 'PcUrl';
    }
  }
};
</script>

<style lang="scss">
.job-notification-item {
  margin: 10px;
  padding: 14px 24px;
  background: #fff;
  cursor: pointer;
  border-radius: 4px;
}
.job-notification-item-new {
  position: absolute;
  top: 11px;
  left: -10px;
  width: 9px;
  height: 9px;
  background: #f44552;
  border: 1px solid #fff;
  border-radius: 50%;
}
.job-notification-item-header {
  position: relative;
  display: inline-block;
  font-size: 16px;
  padding-top: 5px;
  font-weight: bold;
  color: #525252;
  padding-left: 4px;
}
.job-notification-item-btn {
  float: right;
  line-height: 24px;
  width: 30px;
  height: 30px;
  padding: 0;
  margin: 0;
  border: none;
  outline: none;
  background-color: transparent;
  transition: color ease 0.15s;

  i {
    font-size: 14px;
  }

  &:hover {
    color: #e84040;
  }
}
.job-notification-item-info {
  color: #8c8989;
  padding: 4px;
}
.job-notification-item-content {
  padding: 10px 0 14px 4px;
  color: #3e3e3e;
  border-bottom: 1px solid #eae8e8;
  p {
    margin-bottom: 5px;
    word-wrap: break-word;
  }
}
.job-notification-item-footer {
  padding: 14px 0 0 4px;
}
.job-notification-item-detail {
  display: inline-block;
  margin: 0;
  padding: 0;
  outline: none;
  width: 82px;
  height: 28px;
  line-height: 28px;
  border: 1px solid;
  border-radius: 4px;
  text-align: center;
  color: #55b7b4;
}
.job-notification-item-time {
  color: #3e3e3e;
  margin: 0;
}
.over-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
<style lang="scss" scoped>
.open-data {
  margin-right: 0;
}
</style>
